package com.atguigu.gulimall.seckill.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.constant.AuthConstant;
import com.atguigu.common.to.member.MemberRespTo;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Configuration
public class LoginInterceptor implements HandlerInterceptor {
    public static ThreadLocal<MemberRespTo> threadLocal = new ThreadLocal();

    /**
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 添加排除登录验证的路径
         * 拦截器写完了之后一定要配置到webConfig中
         */
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match = antPathMatcher.match("/kill", request.getRequestURI());
        if (match) {
            HttpSession session = request.getSession();
            Object object = session.getAttribute(AuthConstant.LOGIN_USER);

            String s = JSON.toJSONString(object);
            //将json转成需要的对象
            MemberRespTo member = JSONObject.parseObject(s, MemberRespTo.class);
            if (member != null) {
                threadLocal.set(member);
                return true;
            } else {
                request.getSession().setAttribute("msg", "请先完成登录");
                response.sendRedirect("http://auth.gulimall.com/login.html");
                return false;
            }

        }
        return true;
    }


}
